import { FC, Suspense } from 'react';
import {
  useOutlet,
  unstable_useViewTransitionState,
  json,
  defer,
  useLoaderData,
  Await,
} from 'react-router-dom';
import AwaitChild from './view/await-child';

export const Component: FC = () => {
  const viewTransition = unstable_useViewTransitionState('/about');
  const loaderData = useLoaderData();
  console.log(loaderData);

  const outlet = useOutlet();
  return (
    <div>
      <div
        style={{
          background: viewTransition ? 'red' : 'green',
        }}
      >
        测试 <code>viewTransition</code>
      </div>
      {outlet}

      <h1>使用 Await 组件</h1>
      <Suspense fallback={<h1>loading...</h1>}>
        <Await resolve={loaderData.p2}>
          {/* {(data) => {
            console.log(data);
            return <>revi</>;
          }} */}
          <AwaitChild />
        </Await>
      </Suspense>
    </div>
  );
};

export const loader = async () => {
  const p1 = new Promise((reslove) => {
    setTimeout(() => {
      reslove(
        json({
          name: 'test',
          data: [
            {
              name: 'zhangsan',
            },
            {
              name: 'lisi',
            },
          ],
        })
      );
    }, 1000);
  });
  const p2 = new Promise((reslove) => {
    setTimeout(() => {
      reslove(
        json({
          name: 'test2',
          data: [
            {
              name: 'zhangsan',
            },
            {
              name: 'lisi',
            },
          ],
        })
      );
    }, 2000);
  });
  const users = await p1;
  return defer({
    users,
    p2,
  });
};
